package team.zero.lemon.common.MQ.consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import team.zero.lemon.common.utils.JsonUtils;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.jms.*;
import java.io.Serializable;

/**
 * Created by fangpingxi on 2017/9/23.
 */
public abstract class BaseQueueConsumer<T extends Serializable> {
    @Autowired
    @Qualifier("mqConnectionFactory")
    private ConnectionFactory connectionFactory;
    private MessageConsumer consumer=null;
    private Connection connection = null;
    private Session session = null;

    @PostConstruct
    private void init() {
        try {
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createQueue(getQueueName());
            consumer = session.createConsumer(destination);
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    if (null != message) {
                        try {
                            TextMessage textMessage = (TextMessage) message;
                            T currentMessage = JsonUtils.JsonToObject(textMessage.getText(), getClassType());
                            handleMessage(currentMessage);
                        } catch ( JMSException e ) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        } catch ( JMSException e ) {
            clearResource();
        }
    }

    private void clearResource() {
        if (consumer != null) {
            try {
                consumer.close();
            } catch ( JMSException e ) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch ( JMSException e1 ) {
                e1.printStackTrace();
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch ( JMSException e1 ) {
                e1.printStackTrace();
            }
        }
    }

    @PreDestroy
    private void end() {
        clearResource();
    }


    public abstract String getQueueName();

    public abstract Class<T> getClassType();

    public abstract void handleMessage(T message);
}
